import { Component, OnChanges, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { CommonService } from 'src/app/service/common/common.service';
import { FeeEnquiryService } from 'src/app/service/fee-enquiry/fee-enquiry.service';
import { ReportService } from 'src/app/service/fee-enquiry/report.service';
import { MessageService } from 'src/app/service/message.service';
import { UserBindService } from 'src/app/service/user-bind.service';
import { UserInfoService } from 'src/app/service/user-info/user-info.service';

@Component({
  selector: 'app-self-baodu',
  templateUrl: './self-baodu.component.html',
  styleUrls: ['./self-baodu.component.scss']
})
export class SelfBaoduComponent implements OnInit, OnChanges {

  formData = new FormGroup({
    usageCode: new FormControl('', [
      Validators.required
    ]),
    name: new FormControl({value: '', disabled: true}, [
      Validators.pattern(/^[\u4E00-\u9FA5A-Za-z0-9\s]{1,6}$|^[\u4e00-\u9fa5\s]{1,6}$|^[\dA-Za-z0-9\s]{2,20}$/)
    ]),
    address: new FormControl({value: '', disabled: true}),
    meterNo: new FormControl(''),
    meterAddr: new FormControl({value: '', disabled: true}),
    channelId: new FormControl(),
    num: new FormControl('', [
      Validators.required,
      // Validators.pattern(/^[0-9]+(.[0-9]{1,3})?$/)
      Validators.pattern(/^[0-9][0-9]{0,5}$/)
    ]),
    fileId: new FormControl(),
    month: new FormControl(),
    judgeType: new FormControl('01'),
    isSecret: new FormControl({ value: true, disabled: false }),
  })
  fileIdStr: string = '';

  usageCodeInfo: any = [];

  metorList: any = [];

  submitAvailable = true;
  isPreview = false;
  uploadAvailable = true;
  fileDelAvailable = true;

  title = '自报行度';
  size:any;

  constructor(
    private message: MessageService,
    private reportService: ReportService,
    private router: Router,
    private route: ActivatedRoute,
    public userInfo: UserInfoService,
    private userBind: UserBindService,
    private common: CommonService
  ) { }

  isOrder = 'false';
  ngOnInit() {
    this.common.setRightInfoVisible(true)

    this.route.queryParams.subscribe((res: any) => {
      if(res && res.id){
        this.isOrder = res.isOrder;
        this._isPreview(res.id);
      }else{
        this._getBindList();
        //如果是自报行度新增，则需重置表单-----IE浏览器兼容问题
        this.formData.reset()

      }
    })

    // this.util.getMaxFileSize().subscribe(res => {
    // })
  }

  ngOnChanges(){
  }

  monthChange(date: any): string{
    let result = '';
    if(date !== ''){
      let selectDate = new Date(date);
      let year = selectDate.getFullYear();
      let month = selectDate.getMonth() + 1;
      result = `${year}${month.toString().padStart(2, '0')}`;
    }
    return result;
  }

  // 判断是 详情页面 还是 新增页面
  nzDataLoading = false;
  _isPreview(id: any){
    this.formData.disable({ onlySelf: true });
    this.isPreview = true;
    this.nzDataLoading = true;
    this.reportService.getReportDetailById(id).subscribe(res => {
      this._dealPreview(res);
    }, () => {
      this.nzDataLoading = false;
      this.message.error('查询 自报行度 详情 失败，请刷新重试');
    })
  }
  _dealPreview(res: any){
    this.fileIdStr = res.fileId;
    this.formData.patchValue(res);
    this.nzDataLoading = false;
    this.uploadAvailable = false;
  }

  numValueChange(value: any){
    console.log(value)
    setTimeout(() => {
      if(!isNaN(+value)){
        this.formData.get('num')?.setValue(value)
      }
    }, 200)
  }

  // TODO: 提交功能
  btnLoading = false;
  onSubmit(){
    // console.log(this.formData.value);
    // this.monthChange(this.formData.value.month);

    let controls = this.formData.controls;
    for (let i in controls) {
      controls[i].markAsDirty();
      controls[i].updateValueAndValidity();
    }
    
    for(let i in controls){
      if(controls[i].invalid){
        return ;
      }
    }

    let formData: any = this._dealFormData();
    if(formData.fileId === ''){
      this.message.error('请上传水表照片');
      return;
    }

    // 兼容 海颐 和 营业
    formData.userNo = formData.usageCode
    formData.assetsNo = formData.meterNo
    formData.selfNum = formData.num

    this.btnLoading = true;
    this.reportService.submitReport(formData).subscribe(res => {
      if(res.code === 'OK'){
        this.message.successModal('提交成功', () => {
          this.router.navigate(['/fee-enquiry/baodu-li'])
        });
      }else if(res.code === '12'){
        this.formData.patchValue({
          judgeType: '02'
        })
        this.message.infoModal('首次提交成功，需再次提交')
      }else{
        this.message.info(res.msg)
      }
      this.btnLoading = false;
    }, error => {
      this.btnLoading = false;
      this.message.createErrorMessage(error);
    });
  }

  onReset(){
    this.message.confirmModal('重置将清空所有字段信息，并返回上一页，确认重置吗？', this._reset)
  }
  _reset = () => {
    this.formData.reset();
    history.go(-1);
  }

  _dealFormData(){
    let formData = this.formData.getRawValue();
    console.log(formData)
    formData.month = this.monthChange(new Date())
    // formData.num = formData.num.replace('0', '')
    // formData.name = this.name;
    // formData.address = this.address;
    // formData.meterAddr = this.meterAddr;
    // formData.usageCode = '0011244615'
    formData.fileId = this.fileIdStr;
    formData.channelId = 'D09901';
    formData.isSecret = true
    return formData;
  }

  nzLoading = true;
  _getBindList(){  
    this.userBind._getBindList().subscribe(res => {
      this.usageCodeInfo = res;
      this.nzLoading = false;
    }, error => {
      this.message.createErrorMessage(error);
    })
  }

  onUsageCodeChange(){
    let usageCode: any = this.formData.get('usageCode')?.value;

    this._setNameAndAddress(usageCode);

    // this._setMetorList(usageCode);
  }

  onMeterNoChange(meterNo: string){
    this.formData.get('meterAddr')?.reset();

    let obj: any = this.metorList.filter((item: any) => {
      // return item.meterNo === meterNo;
      return item.madeNo === meterNo;
    })
    if(obj.length){
      this.formData.patchValue({
        meterAddr: obj[0]?.meterAddr
      })
    }
  }

  _setNameAndAddress(usageCode: string){

    this.formData.get('name')?.reset();
    this.formData.get('address')?.reset();

    let obj: any = this.usageCodeInfo.filter((item: any) => {
      return item.usageCode === usageCode;
    })
    if(obj.length){
      this.formData.patchValue({
        name: obj[0].name,
        address: obj[0].address
      })
    }
  }
  _setMetorList(usageCode: string){

    this.metorList = [];
    this.formData.get('meterNo')?.reset();
    this.formData.get('meterAddr')?.reset();

    let temp: any = this.usageCodeInfo.filter((item: any) => {
      return item.usageCode === usageCode;
    })
    if(temp.length){
      this.metorList = temp[0].meterList;
      this.formData.patchValue({
        // meterNo: this.metorList[0].meterNo,
        meterNo: this.metorList[0].madeNo,
        meterAddr: this.metorList[0].meterAddr,
      })
    }
  }

  uploadBack(e: string){
    this.fileIdStr = e;
  }

  doBack(){
    if(this.isOrder === 'true'){
      this.router.navigate(['/me/order-query']);
    }else{
      history.go(-1);
    }
    
  }

}


